package com.test;

import org.apache.commons.io.FileUtils;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class FileLockExample {
    public static void main(String[] args) {
        try {
            // 创建一个随机访问文件对象
            RandomAccessFile file = new RandomAccessFile("example.txt", "rw");
            // 获取文件通道
            FileChannel channel = file.getChannel();

            // 尝试获取文件锁
            FileLock lock = channel.lock();
            try {
                // 在这里执行需要文件锁定的操作
                System.out.println("File is locked.");

                // 模拟一些处理过程
                Thread.sleep(10000);
                FileUtils.moveFile(new File("example.txt"), new File("example_backup.txt"));

            } finally {
                // 释放锁
                lock.release();
                System.out.println("File lock released.");
            }

            new Thread(() ->{

                try (BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("example.txt")))){

                    String line;
                    while((line = bufferedReader.readLine()) != null){
                        System.out.println(line);
                    }


                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }


            }).start();

            // 关闭文件通道和文件
            channel.close();
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}